//
//  Alert.swift
//  
//
//  Created by bo wang on 2020/11/30.
//  Copyright © 2020 wangbo. All rights reserved.
//

import Foundation
import UIKit

typealias Alert = UIAlertController

extension UIAlertController {
    
    @discardableResult
    static func alert(_ message: String,
                      from: UIViewController? = nil,
                      completion: (() -> Void)? = nil)
    -> UIAlertController {
        let l = UIAlertController(title: message, message: nil, preferredStyle: .alert)
        l.addAction(.init(title: "Done", style: .default, handler: { _ in
            completion?()
        }))
        let p = from ?? AppDelegate.shared.window?.topVC
        p?.present(l, animated: true, completion: nil)
        return l
    }

    @discardableResult
    static func confirm(_ title: String? = nil,
                        message: String? = nil,
                        from: UIViewController? = nil,
                        confirmBtn: String = "Done",
                        completion: @escaping (Bool) -> Void)
    -> UIAlertController {
        let l = UIAlertController(title: title, message: message, preferredStyle: .alert)
        l.addAction(.init(title: "Cancel", style: .cancel, handler: { _ in
            completion(false)
        }))
        l.addAction(.init(title: confirmBtn, style: .destructive, handler: { _ in
            completion(true)
        }))
        if let p = from {
            p.present(l, animated: true, completion: nil)
        } else {
            AppDelegate.shared.window?.topVC?.present(l, animated: true, completion: nil)
        }
        return l
    }
}
